package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"time"
)

var (
	gdisd       int
	gIdIndex    int64
	gTableCount int64
)

const (
	max_db_count = 86400 //2*60minutes*24hours*30days
	//max_db_count = 200 //2*60minutes*24hours*30days for test
)

type IpccStatusCallcenter struct {
	Id          int64
	CallNumbers int       `orm:"description(当前并发数量);"`
	RegAgent    int       `orm:"description(注册sip账号数量);"`
	UpdateTime  time.Time `orm:"description(更新时间,每30s更新一次);type(datetime)"`
}

func (s *IpccStatusCallcenter) TableName() string {

	dbName := fmt.Sprintf("ipcc_status_callcenter_%d", gdisd)
	return dbName
}

func RegisterStatus(dsid int) {
	gdisd = dsid
	orm.RegisterModel(new(IpccStatusCallcenter))
}

func UpdateStatus(calls, regAgent int) {

	s := &IpccStatusCallcenter{
		Id:          gIdIndex,
		CallNumbers: calls,
		RegAgent:    regAgent,
		UpdateTime:  time.Now(),
	}

	o := orm.NewOrm()

	//初始化
	if gIdIndex == 0 {
		count, err := o.QueryTable(new(IpccStatusCallcenter)).Count()
		if err != nil {
			logs.Error("query from db err:%v", err)
			return
		}
		logs.Debug("初始化监控表单数据条数:%v", count)
		gTableCount = count

		if count == 0 || count < max_db_count {
			//一条数据也没有，插入新数据；表数据未满，新增数据
			gIdIndex, err = orm.NewOrm().Insert(s)
			if err != nil {
				logs.Error("insert wrong:%v", err)
				return
			}
			gTableCount++
		} else { //数据表满了，需要从最老的条数据开始更新

			//获取最老的数据
			err = o.QueryTable(new(IpccStatusCallcenter)).
				OrderBy("UpdateTime").
				Offset(0).
				Limit(1).One(s)
			logs.Debug("get oldest records:%v", s)

			s.CallNumbers = calls
			s.RegAgent = regAgent
			s.UpdateTime = time.Now()
			gIdIndex = s.Id

			_, err = o.Update(s, "CallNumbers", "RegAgent", "UpdateTime")
			if err != nil {
				logs.Error("update %v err: %v", s, err)
				return
			}

			indexIncrease()
		}
	} else {
		//数据表未满，则新增数据
		if gTableCount < max_db_count {
			s.Id = 0
			id, err := orm.NewOrm().Insert(s)
			if err != nil {
				logs.Error("insert wrong:%v", err)
				return
			}

			gIdIndex = id
			gTableCount++

		} else {
			//数据表未满，则更新数据
			s.Id = gIdIndex
			orm.NewOrm().Update(s)

			indexIncrease()
		}
	}
}

func indexIncrease() {

	if gIdIndex >= max_db_count {
		logs.Debug("loop to begin from:%v", gIdIndex)
		gIdIndex = 1
	} else {
		gIdIndex++
	}
}

func RecoverCount() {
	s := &IpccStatusCallcenter{}

	now := time.Now()
	err := orm.NewOrm().QueryTable(new(IpccStatusCallcenter)).Filter("UpdateTime__lt", now).Distinct().One(s)
	if err != nil {

	}
}
